const { parentPort } = require("worker_threads");
const moment = require("moment");
const { checkFolderExist, setParams, htmlParser } = require("../utils");
const path = require("path");
const colors = require("colors");
const CreateInter = require("../axios.config");
const axios = CreateInter();
const fs = require("fs");
const os = require("os");
const {
  weatherQueryUrl,
  weatherStationUrl,
  savePath,
  stationCollectionFileName,
} = require("../config");
const HTMLParser = require("node-html-parser");
const { TaskMessageEmit } = require("../event");
parentPort.on(
  "message",
  async ({
    stationID: stationID,
    stationName: stationName,
    cityName: cityName,
  }) => {
    try {
      const date = moment();
      const saveStationPath = path.join(
        ...[savePath, date.year().toFixed(), date.format("YYYY-MM-DD")]
      );
      checkFolderExist(saveStationPath, true);

      console.log(`开始找寻${colors.cyan(stationName)}站点的数据`);
      const res = await axios.post(
        weatherQueryUrl,
        setParams(stationName, cityName),
        {
          responseType: "json",
        }
      );
      if (res?.status === 200) {
        const placeId =
          res.data?.dal?.getSunV3LocationSearchUrlConfig?.[
            `language:zh-CN;locationType:locale;query:${stationName}, ${cityName}`
          ]?.data?.location?.placeId?.[0];

        const htmlRes = await axios.get(`${weatherStationUrl}${placeId}`, {
          responseType: "document",
        });
        if (htmlRes?.status === 200) {
          const root = HTMLParser.parse(htmlRes.data);
          const json = htmlParser(root);

          if (json) {
            const filePath = path.join(
              ...[saveStationPath, stationID + "." + stationName + ".json"]
            );
            const stationCollectionPath = path.join(
              ...[saveStationPath, stationCollectionFileName]
            );

            // const stationData = {};

            const {
              dal: {
                getSunV3LocationPointUrlConfig,
                getSunV3HourlyForecastUrlConfig,
              },
            } = JSON.parse(JSON.parse(json));
            const { longitude, latitude, displayName, adminDistrict, city } =
              getSunV3LocationPointUrlConfig[
                `language:zh-CN;placeId:${placeId}`
              ]?.data?.location;
            const {
              cloudCover,
              pressureMeanSeaLevel,
              qpf,
              relativeHumidity,
              temperature,
              temperatureDewPoint,
              visibility,
              windDirection,
              windSpeed,
              validTimeLocal,
            } = Object.entries(getSunV3HourlyForecastUrlConfig)[0][1]?.data;
            // stationData.header = {
            //   lng: longitude,
            //   lat: latitude,
            //   displayName: displayName,
            //   province: adminDistrict,
            //   city: city,
            // };

            // stationData.data = {
            //   TCDC: cloudCover,
            //   PRMSL: pressureMeanSeaLevel,
            //   QPF: qpf,
            //   RH: relativeHumidity,
            //   TMP: temperature,
            //   DPT: temperatureDewPoint,
            //   VIS: visibility,
            //   UGRD: windDirection,
            //   VGRD: windSpeed,
            // };

            const content = [
              `"${stationID}"`,
              `"${displayName}"`,
              `"${city}"`,
              `"${adminDistrict}"`,
              `"${longitude}"`,
              `"${latitude}"`,
              `"${JSON.stringify(cloudCover)}"`,
              `"${JSON.stringify(pressureMeanSeaLevel)}"`,
              `"${JSON.stringify(qpf)}"`,
              `"${JSON.stringify(relativeHumidity)}"`,
              `"${JSON.stringify(temperature)}"`,
              `"${JSON.stringify(temperatureDewPoint)}"`,
              `"${JSON.stringify(visibility)}"`,
              `"${JSON.stringify(windDirection)}"`,
              `"${JSON.stringify(windSpeed)}"`,
              `"${JSON.stringify(
                validTimeLocal.map((i) => moment(i).toDate().getTime())
              )}"`,
              os.EOL,
            ];

            fs.appendFile(stationCollectionPath, content.join(","), (err) => {
              if (err) {
                console.log(
                  `合成数据${stationCollectionPath}失败;失败原因:${err}`
                );
              }
              console.log(`合成数据${stationCollectionPath}成功`);
            });

            fs.writeFile(
              filePath,
              JSON.stringify(JSON.parse(JSON.parse(json)), "", "\t"),
              (err) => {
                if (err) {
                  console.error(err);
                  parentPort.postMessage({
                    status: 400,
                    data: err,
                  });
                } else {
                  console.log(`保存${colors.cyan(stationName)}数据成功`);
                  parentPort.postMessage({
                    status: 200,
                    data: "保存数据成功",
                  });
                }
              }
            );
          }
        } else {
          console.log(
            `找寻站点${colors.bgRed(
              stationName
            )}的数据失败,失败原因:${colors.bgRed(htmlRes?.statusText)}`
          );
          parentPort.postMessage({
            status: 404,
            data: htmlRes?.statusText,
          });
        }
      } else {
        console.log(
          `找寻站点${stationName}的数据失败,失败原因:${res?.statusText}`
        );
        parentPort.postMessage({
          status: 404,
          data: res?.statusText,
        });
      }
    } catch (error) {
      console.error(`找寻站点${stationName}的数据失败,失败原因:${error}`);
      parentPort.postMessage({
        status: 404,
        data: error,
      });
    }
  }
);
